package com.zl.org.service.impl;

import com.zl.basic.service.impl.BaseServiceImpl;
import com.zl.basic.util.MD5Utils;
import com.zl.basic.util.StrUtils;
import com.zl.org.domain.Employee;
import com.zl.org.mapper.EmpMapper;
import com.zl.org.service.EmpService;
import com.zl.user.domain.LoginInfo;
import com.zl.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class EmpServiceImpl extends BaseServiceImpl<Employee> implements EmpService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private EmpMapper empMapper;

    @Override
    public void save(Employee employee) {
        // 1.处理密码和盐值
        String salt = StrUtils.getComplexRandomString(32);
        String md5PWD = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5PWD);
        LoginInfo loginInfo = employee2LoginInfo(employee);
        loginInfoMapper.save(loginInfo);
        employee.setLogininfo_id(loginInfo.getId());
        super.save(employee);
        if (employee.getRole_id()!=null){
            empMapper.addEmpRole(employee.getId(),employee.getRole_id());
        }

    }

    private LoginInfo employee2LoginInfo(Employee employee) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(employee,loginInfo);
        loginInfo.setType(0);
        return loginInfo;
    }


    @Override
    public void remove(Long id) {
        empMapper.delEmpRole(id);
        Employee employee = empMapper.loadById(id);
        loginInfoMapper.remove(employee.getLogininfo_id());

        super.remove(id);
    }

    @Override
    public void update(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5PWD = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5PWD);
        LoginInfo loginInfo = employee2LoginInfo(employee);
        Long logininfo_id = empMapper.loadById(employee.getId()).getLogininfo_id();
        loginInfo.setId(logininfo_id);
        loginInfoMapper.update(loginInfo);

        empMapper.delEmpRole(employee.getId());
        if (employee.getRole_id()!=null){
            empMapper.addEmpRole(employee.getId(),employee.getRole_id());
        }
        super.update(employee);

    }

    @Override
    public List<Employee> list(Long shopId) {
        return  empMapper.list(shopId);
    }
}
